package com.example.ai.service;

import com.example.ai.model.User;
import com.example.ai.model.UserStatistics;
import com.example.ai.repository.UserRepository;
import com.example.ai.repository.UserStatisticsRepository;
import com.example.ai.repository.QuestionRepository;
import com.example.ai.repository.WrongQuestionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Transactional
public class StatisticsService {

    private final UserStatisticsRepository statisticsRepository;
    private final UserRepository userRepository;
    private final QuestionRepository questionRepository;
    private final WrongQuestionRepository wrongQuestionRepository;

    @Transactional(readOnly = false)
    public Map<String, Object> getUserStatistics(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found: " + username));

        // 获取总提问次数
        long totalQuestions = questionRepository.countByUser(user);
        
        // 获取错题数量
        long wrongQuestionsCount = wrongQuestionRepository.countByUser(user);
        
        // 获取今日提问次数
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        long todayQuestions = questionRepository.countByUserAndCreatedAtAfter(user, startOfDay);

        // 获取或创建用户统计信息
        UserStatistics stats = statisticsRepository.findByUser(user)
                .orElseGet(() -> createNewUserStatistics(user));

        Map<String, Object> response = new HashMap<>();
        response.put("totalQuestions", totalQuestions);
        response.put("wrongQuestionsCount", wrongQuestionsCount);
        response.put("todayQuestions", todayQuestions);
        response.put("accuracy", Math.round(stats.getAccuracy() * 100.0) / 100.0);
        
        // 转换总时间为可读格式
        long totalSeconds = stats.getTotalTimeInSeconds();
        String totalTime = String.format("%dh %dm", 
            totalSeconds / 3600, 
            (totalSeconds % 3600) / 60);
        response.put("totalTime", totalTime);
        
        return response;
    }

    @Transactional(readOnly = false)
    public void updateStatistics(String username, boolean isCorrect, long timeSpentSeconds) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found: " + username));
        
        UserStatistics stats = statisticsRepository.findByUser(user)
                .orElseGet(() -> createNewUserStatistics(user));
        
        stats.setTotalQuestions(stats.getTotalQuestions() + 1);
        if (isCorrect) {
            stats.setCorrectAnswers(stats.getCorrectAnswers() + 1);
        } else {
            stats.setWrongAnswers(stats.getWrongAnswers() + 1);
        }
        stats.setTotalTimeInSeconds(stats.getTotalTimeInSeconds() + timeSpentSeconds);
        
        statisticsRepository.save(stats);
    }

    public UserStatistics createNewUserStatistics(User user) {
        UserStatistics stats = new UserStatistics();
        stats.setUser(user);
        return statisticsRepository.save(stats);
    }
} 